package org.luo.iot.domain.device;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {
    @Override
    @Transactional
    public void deductPrice(Device device) {
        Device d = this.getById(device.getId());
        if(d == null){
            throw new RuntimeException("设备不存在");
        }
        if(d.getPrice() < device.getPrice()){
            throw new RuntimeException("价格不足");
        }

//        baseMapper.deductPrice(device.getId(), device.getPrice());

        int remain = d.getPrice() - device.getPrice();
        lambdaUpdate()
                .set(Device::getPrice, remain)
                .eq(Device::getId, device.getId())
                .eq(Device::getPrice, d.getPrice())
                .update();
    }

    @Override
    public List<Device> getDeviceList(DeviceQuery dq) {

        List<Device> list = lambdaQuery()
                .like(dq.getName() != null, Device::getName, dq.getName())
                .like(dq.getSerialNo() != null, Device::getSerialNo, dq.getSerialNo())
                .ge(dq.getMinPrice() != null, Device::getPrice, dq.getMinPrice())
                .le(dq.getMaxPrice() != null, Device::getPrice, dq.getMaxPrice())
                .list();
        return list;
    }

    @Override
    public Page<Device> page(DeviceQuery dq){
        Page<Device>  page = Page.of(dq.getPageNum(), dq.getPageSize());
        page = lambdaQuery()
                .like(dq.getName() != null, Device::getName, dq.getName())
                .like(dq.getSerialNo() != null, Device::getSerialNo, dq.getSerialNo())
                .ge(dq.getMinPrice() != null, Device::getPrice, dq.getMinPrice())
                .le(dq.getMaxPrice() != null, Device::getPrice, dq.getMaxPrice())
                .page(page);


        return page;
    }
}
